package com.walker.kuyun.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.walker.kuyun.App
import com.walker.kuyun.R
import com.walker.kuyun.bean.VideoCoverBean
import com.walker.kuyun.config.Api
import com.walker.kuyun.util.JsoupUtil
import com.walker.kuyun.util.ParseHtmlUtil.parseLpic
import com.walker.kuyun.util.Util.showToastOnThread
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jsoup.select.Elements
import java.lang.Exception
import java.util.*


class MonthViewModel : ViewModel() {
    var monthVideoList: MutableList<VideoCoverBean> = ArrayList()
    var mldMonthAnimeList: MutableLiveData<Boolean> = MutableLiveData()

    fun getMonthAnimeData(partUrl: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val url = Api.MAIN_URL + partUrl
                val document = JsoupUtil.getDocument(url)
                val areaElements: Elements = document.getElementsByClass("area")
                monthVideoList.clear()
                for (i in areaElements.indices) {
                    val areaChildren: Elements = areaElements[i].children()
                    for (j in areaChildren.indices) {
                        when (areaChildren[j].className()) {
                            "lpic" -> {
                                monthVideoList.addAll(parseLpic(areaChildren[j], url))
                            }
                        }
                    }
                }
                mldMonthAnimeList.postValue(true)
            } catch (e: Exception) {
                monthVideoList.clear()
                mldMonthAnimeList.postValue(false)
                e.printStackTrace()
                (App.getApp().getString(R.string.get_data_failed) + "\n" + e.message).showToastOnThread()
            }
        }
    }

    companion object {
        const val TAG = "MonthAnimeViewModel"
    }
}